package csc.daonjpa.java.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import csc.daonjpa.java.domain.TargetAccount;


@Repository
public class TargetAccountDAO {
	
	@PersistenceContext private EntityManager em;
	
	/**
	 * Get the target account based on its account number
	 * @param accountNumber
	 * @return
	 */
	@Transactional
	public TargetAccount getTargetAccountByAccNum(String accountNumber){
//		EntityManager em = TransactionManager.getEntityManager();
		TypedQuery<TargetAccount> query = null;
		try {
			query = em.createQuery(
					"SELECT a FROM TargetAccount a WHERE accountNumber = :accNum",
					TargetAccount.class).setParameter("accNum", accountNumber);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Remember to check null later
		List<TargetAccount> tarAccounts = query.getResultList();
		if (!tarAccounts.isEmpty()) {
			return tarAccounts.get(0);
		}
		return null;
	}
	
	/**
	 * Get target account based on its id
	 */
	@Transactional
	public TargetAccount getTargetAccountByAccId(int accId) {
//		EntityManager em = TransactionManager.getEntityManager();
		TypedQuery<TargetAccount> query = null;
		try {
			query = em.createQuery(
					"SELECT a FROM TargetAccount a WHERE id = :accId",
					TargetAccount.class).setParameter("accId", accId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Remember to check null later
		List<TargetAccount> accounts = query.getResultList();
		if (!accounts.isEmpty()) {
			return accounts.get(0);
		}
		return null;
	}

	/**
	 * Get all target account in the db
	 * @return list of accounts
	 */
	@Transactional
	public List<TargetAccount> getAllTargetAccounts() {
//		EntityManager em = TransactionManager.getEntityManager();
		TypedQuery<TargetAccount> query = null;
		try {
			query = em.createQuery("SELECT a FROM TargetAccount a",TargetAccount.class);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Remember to check null later
		List<TargetAccount> accounts = query.getResultList();
		return accounts;
	}
	
}
